import * as echarts from "echarts";
import lessModule from "./index.module.less"
import { useEffect, useState } from "react"
import { $echartsData, $eventBus, $switch_index, $switch_mode, $switch_tagName } from "../../../../../../common/utils";
import { modeType } from "../../../../../../common/interface";
import { text } from "stream/consumers";
// 主页-分析组件-图标多线组件
interface homePageAnalysisComponentChartLinesComponentComponentInterface {
    isWarningLine: boolean
    mode?: modeType
    paramsData: object
    sourceData: object
}
const HomePage_AnalysisComponent_ChartLinesComponent: React.FC<homePageAnalysisComponentChartLinesComponentComponentInterface> = (props) => {

    let [echartsLine, setEchartsLine] = useState<echarts.ECharts>()
    const init_echarts = () => {
        echartsLine = echarts.init(document.getElementById("echartLines") as HTMLElement)
        setEchartsLine(echartsLine)
        window.addEventListener("resize", () => {
            echartsLine?.resize();
        })

        draw_echarts()
    }

    const draw_echarts = () => {
        const echartsOption = {
            tooltip: {
                trigger: "axis",
                backgroundColor: "#FFFFFF",
                textStyle: {
                    fontSize: 12,
                    fontWeight: 400,
                },
                axisPointer: {
                    lineStyle: {
                        type: "solid",
                        color: "rgba(64, 93, 249, 0.5)",
                    }
                },
                formatter(list: Array<Object>) {
                    emit_cursorValue(list)
                    return `<div class="homePage-chartTooltip">
                    ${list.map((item, idx) => {
                        return `
                        <div style="margin-top:${idx ? 20 : 0}px">
                            <div class="homePage-chartTooltip__title">${item['axisValue']}</div>
                                <div class="homePage-chartTooltip__row">
                                    <div class="chartTooltip-row__legend" style="background-color:${$echartsData["chartLineColorList"][idx]}"></div>
                                    <span>${item["seriesName"]}</span>
                                    <span style="color:${$echartsData["chartLineColorList"][idx]}">${typeof (item["value"]) === "number" ? item["value"].toFixed(2) : "-"}</span>
                                </div>     
                        </div>`
                    }).join("")
                        }
                    </div>`;
                },
            },
            legend: {
                left: "left",
                icon: "rect",
                padding: [0, 40],
                itemWidth: 10,
                itemHeight: 2,
                textStyle: {
                    color: "rgba(0, 0, 0, 0.85)"
                }
            },
            grid: {
                top: 70,
                left: 54,
                bottom: 150,
                right: 60,
            },
            xAxis: (() => {
                const xAxisList: Array<object> = [];


                ["time", "bTime"].map((item: string, idx: number) => {
                    if (item in props.sourceData) {

                        xAxisList.push(
                            {
                                type: "category",
                                data: props.sourceData[item],
                                boundaryGap: false,
                                position: "bottom",
                                axisLine: {
                                    show: true,
                                    lineStyle: {
                                        color: "rgba(65, 97, 128, 0.45)",
                                    },
                                },
                                axisTick: {
                                    show: true,
                                    lineStyle: {
                                        color: "rgba(65, 97, 128, 0.35)",
                                    },
                                },

                                axisLabel: {
                                    align: "center",
                                    color: "rgba(0, 0, 0, 0.65)",
                                    margin: idx ? 40 : 20,
                                    fontSize: 10,
                                    showMinLabel: true,
                                    showMaxLabel: true,
                                    formatter: (() => {
                                        return (labelItem: Object, idx: number) => {
                                            const isStart = !idx
                                            const isLast = idx === props.sourceData[item]?.length - 1;
                                            const label = isStart ? `{start|${labelItem}}` : isLast ? `{last|${labelItem}}` : labelItem;
                                            return label;
                                        };
                                    })(),
                                    interval: props.sourceData[item]?.length / 4,
                                    rich: {
                                        start: {
                                            width: 0,
                                            fontSize: 10,
                                            align: "left",
                                        },
                                        last: {
                                            width: 0,
                                            fontSize: 10,
                                            align: "right",
                                        },
                                    },
                                },
                            }
                        )

                    }
                })
                return xAxisList
            })(),
            yAxis: {
                type: "value",
                axisLabel: {
                    fontSize: 12,
                    fontWeight: 400,
                    color: "rgba(0, 0, 0, 0.65)",
                },
                splitLine: {
                    lineStyle: {
                        color: "rgba(65, 97, 128, 0.1519)",
                    },
                },
            },
            dataZoom: [
                {
                    type: 'slider',
                    ...$echartsData["zoomAxisConfigureData"]
                },
                {
                    type: "inside",
                    start: 0,
                    end: 100,
                },
            ],
            series: (() => {
                const seriesList: Array<object> = [];
                (props.mode ? props.paramsData[$switch_mode(props.mode, "deviceList", "index")] : $switch_tagName(props.paramsData["tagName"], props.paramsData["deviceList"], props.paramsData["index"], ["A", "B"]))?.map((item: string, idx: number) => {
                    seriesList.push(
                        {
                            name: `${item}${props.paramsData["tagName"].includes("双时段") && idx < 2 ? "时段" : ""}`,
                            data: props.mode ? $switch_mode(props.mode, Object.values(props.sourceData["device" in props.sourceData ? "device" : props.paramsData["index"][0]] ?? {})[idx], Object.values(props.sourceData[item] ?? [])[0]) :
                                $switch_tagName(props.paramsData["tagName"], Object.values(props.sourceData["device" in props.sourceData ? "device" : props.paramsData["index"][0]] ?? {})[idx], Object.values(props.sourceData[item] ?? [])[0], Object.values(props.sourceData["device" in props.sourceData ? "device" : props.paramsData["index"][0]] ?? {})[idx]),
                            type: "line",
                            color: $echartsData["chartLineColorList"][idx],
                            symbol: "none",
                            // smooth: true,
                            animation: false,
                            markLine: props.isWarningLine ? {
                                silent: true,
                                symbol: "none",
                                data: [
                                    {
                                        yAxis: 30,
                                        lineStyle: {
                                            color: $echartsData["charWarningLineColorList"][0]
                                        },
                                        label: {
                                            color: $echartsData["charWarningLineColorList"][0],
                                            formatter: `一级预警(${30})`
                                        }
                                    },
                                    {
                                        yAxis: 20,
                                        lineStyle: {
                                            color: $echartsData["charWarningLineColorList"][1]
                                        },
                                        label: {
                                            color: $echartsData["charWarningLineColorList"][1],
                                            formatter: `二级预警(${20})`
                                        }
                                    },
                                ],
                                lineStyle: {
                                    type: 'solid',
                                    width: 1
                                },
                            } : {},
                        }
                    )

                })
                return seriesList
            })(),
        }
        echartsLine?.setOption(echartsOption);
    }
    const emit_cursorValue = (list: Array<object>) => {
        setTimeout(() => {
            $eventBus.emit("cursorValue", { source: "HomePage_AnalysisComponent_ChartLinesComponent", explain: "图表游标值已发送！", data: { list: list.map((item: object) => typeof (item["value"]) === "number" ? item["value"].toFixed(2) : "-") } })
        });
    }
    const mouseOut_chart = () => {
        emit_cursorValue(props.sourceData["otherList"].map((item: object) => "-"))
    }

    useEffect(() => {
        init_echarts()
        return () => {
            echartsLine?.dispose()
        }
    }, [props.isWarningLine, props.sourceData])

    return (
        <div id="echartLines" className={lessModule["homePageAnalysisComponentChartLinesComponent"]} onMouseOut={mouseOut_chart}></div>
    )
}



export default HomePage_AnalysisComponent_ChartLinesComponent